/*-----------------------------------------------------
    NewsLister admin.js 
	
    @package NewsLister
	@since 1.0
	
	@version    1.0.2
	@copyright Tenderfeel
	@author Tenderfeel(tenderfeel@gmail.com)
	@link http://tenderfeel.xsrv.jp/ 
	
	[2010/03/15] 1.0.2
	 * HELPと編集ボタン追加
	 * MooRainbow用script、css link
	 
	1.0.0 -> 1.0.1 都度リクエストする方法に戻した
------------------------------------------------------*/

var NLConfig = new Hash({
						
	logareaID:"logarea",//ログ表示要素のID
	messageID:"message",//メッセージ要素のID
	postfile:'include/post.php',//post.phpまでのパス
	logmax:10, //ログの最大表示数
	dateformat:"%Y/%m/%d @ %H:%M",//日時フォーマット
	loader:'<img src="include/images/loader.gif" width="128" height="15" alt="Loading" />'

});

/*----------------------------------------------------*/

window.addEvent('domready', function(){
									 
	
	//ログ表示要素
	var logarea = $(NLConfig.logareaID);
	var logareaTween = new Fx.Tween(logarea,{'property':"opacity",link:"cancel"});
	
	//メッセージ要素
	var message = $(NLConfig.messageID);
	var messageEff = new Fx.Reveal(message,{link:'chain'});
	message.hide = function(){ (function(){messageEff.dissolve()}).delay(2000)};
	
	
	//削除ボタン
	var del = new Element("span",{ html:"[x]","class":"del",'title':'この投稿を削除'});
	
	//ローディングバー
	var loader = new Element("p",{
				 'id':"loader",
				 'html':NLConfig.loader,
				 "morph":{duration: 500}
			});
	
	loader.inject(logarea,"before");
	
	//ヘルプ
	var help = $("help");
	//テキストエリア
	var textarea = $("comment");
	
	$("helpLink").addEvent("click",function(e){
		e.stop();
		help.setStyle("display",(help.getStyle("display")=="none")?"block":"none");
	
	});
	
	var textColor = new MooRainbow('txt-color', {
		'imgPath':'include/mooRainbow/images/',
		'startColor': [0, 0, 255],
		onComplete: function(color) {
			surroundHTML("{"+color.hex+":","}", textarea);
		}
	});
	
	$("txt-strong").addEvent('click',function(e){
		e.stop();
		surroundHTML("||","||",  textarea);
	});
	
	$("txt-em").addEvent('click',function(e){
		e.stop();									
		surroundHTML("//","//", textarea);
	});
	
	$("txt-link").addEvent('click',function(e){
		e.stop();
		href = window.prompt("URLを入力して下さい","");
		surroundHTML("[[",":"+href+"]]", textarea);
	});
	
	//保存/////////////////////////////////////////	
	$("save").addEvent("click",function(e){
		e.stop();
		
		var year = $("year"); //年
		var month = $("month"); //月
		var day = $("day"); //日
		var hour = $("hour"); //時
		var minit = $("min"); //分
		var comment = textarea;//本文
		
		var dataSave = new Request.JSON({
			url:NLConfig.postfile,
			method: 'post',
			data:{"mode":"save",
					"year":year.value,
					"month":month.getSelected()[0].value,
					"day":day.value,
					"hour":hour.value,
					"min":minit.value,
					"comment":comment.value
			},
			onRequest: function(){
				var dd = new Date();
				hour.value = dd.get('hr');
				minit.value = dd.get('min');
				comment.value = "";
			},
			onSuccess: function(txt) {
				//削除ボタン
			 	var copy = del.clone();
			 	copy.addEvent("click",function(){
							var self = this.getParent();
							var myEffect = new Fx.Morph(self,{onComplete:function(){self.destroy();}});
							 myEffect.start({
								'margin': 0,
								'padding': 0,
								'height': 0,
								'opacity': 0
							});
							 //削除リクエスト送信を仕込んどく
							 deleteRequest.send({data:{"mode":"delete","index":txt.id}});	  
						});
				
				
				//送信した内容の段落作成
			  	var parag = new Element("p",{html:"<span class=\"date\">"+showLocalDate(txt.date)+"</span><strong>"+txt.comment+"</strong>"}).grab(copy,"top").fade("hide").inject(logarea,"top");
				
				parag.fade("in");
				
			},
			onFailure: function() {
				 message.set("html","保存時にエラーが発生しました");
				 messageEff.reveal().chain(message.hide);
			}
		  })
	
		if(comment.value!=""){
			dataSave.send();
			message.set("html","保存しました");
			messageEff.reveal().chain(message.hide);

		}else{
			message.set("html","コメントを入力してください");
			messageEff.reveal().chain(message.hide);
		}
		
	});
	
	//ログの表示////////////////////////////////////
	var loading = new Request.JSONP({
		url:NLConfig.postfile,
		method:'get',
		onRequest: function(){
			loader.morph({'height':15, 'opacity': 1, 'padding': 20});
		},
		onSuccess: function(txt) {
			logarea.getChildren().destroy();//既存段落削除
			
			loader.morph({'height':0, 'opacity': 0, 'padding': 0});//ローディングバー非表示
			
			if($type(txt.items) != false){
				
				$each(txt.items,function(item,i){
					//削除ボタン
					var copy = del.clone();
					copy.addEvent("click",function(){
								var self = this.getParent();
								
								 deleteRequest.send({data:{"mode":"delete","index":item.id}});	  
								 
								new Fx.Morph(self,{
									onComplete:function(){
										self.destroy();
										if(logarea.getChildren().length === 0){
											logarea.store("page",0);
											logreset(0); //段落0ならリロード
										}
									}
								}).start({
									'margin': 0,
									'padding': 0,
									'height': 0,
									'opacity': 0
								});
							});
					
						//段落作成
						new Element("p",{html:"<span class=\"date\">"+showLocalDate(item.date)+"</span><strong>"+item.comment+"</strong>"}).grab(copy,"top").inject(logarea);
						
					});
						
					createNavi(txt.pagenum+2);
					
				
				}else if(txt.current === 0){
					logarea.getChildren().destroy();//既存段落削除
					logarea.set("html","<div class=\"nodata\">No Data</div>");
				}else{
					logreset(logarea.retrieve("page"));
				}
		},
		onFailure: function() {
			message.set("html","読み込み時にエラーが発生しました");
			messageEff.reveal().chain(message.hide);
		}
	});
	
	
	//ページナビ//////////////////////////////////
	var createNavi = function(limit){
		
		var pageNavi = $("pageNavi") ? $("pageNavi") : new Element("p",{'id':"pageNavi", 'text':"Page:"});
		pageNavi.inject(logarea,"before");
		
		 pageNavi.getChildren("a").destroy();
		
		for(i=1; i < limit ; i++){//リンクの作成
				new Element("a",{'text':i, 'href':"#", 'class':"p" + i,
							events:{ 
								click:function(e){
									e.stop();
									pageNavi.getChildren().setStyle("background-color","#fff");
									this.setStyle("background-color","yellow");
									logarea.store("page",this.text-1);
									logreset(this.text-1);
								}
							} 
						}).inject(pageNavi);
				
				if((i % 20)==0) {
					new Element("br").inject(pageNavi);
				}
			}
			
			
			
			$("pageNavi").getChildren("a.p"+(logarea.retrieve("page").toInt()+1)).setStyle("background-color","yellow");
		
	}
	
	
	loading.send({data:{"mode":"load","page":0}});
	logarea.store("page",0);
	
	//リロード/////////////////////////////////////
	
	$("reload").addEvent("click",function(){
			resetflag = true;
			logreset(logarea.retrieve("page"));
	});
	
	//削除/////////////////////////////////////////
	var deleteRequest = new Request({
							url:NLConfig.postfile,
							method: 'post',
							onSuccess: function(txt) {
								message.set("html",txt);
								messageEff.reveal().chain(message.hide);
							},
							onFailure: function() {
								message.set("html","削除時にエラーが発生しました");
								messageEff.reveal().chain(message.hide);
							}
						});
	//リセット/////////////////////////////////////
	var logreset = function(page){
		logareaTween.start(0)
		.chain(function(){loading.send({data:{"mode":"load","page":page}});logareaTween.start(1);});
		
	}

});

function showLocalDate(timestamp)
{
  var dt = new Date(timestamp * 1000);
  return dt.format(NLConfig.dateformat);
  //return dt.getFullYear()+"/"+(dt.getMonth()+1)+"/"+dt.getDate()+" @"+dt.getHours()+":"+dt.getMinutes();
} 


//original:http://archiva.jp/web/javascript/getRange_in_textarea.html
function getAreaRange(obj)
{
	var pos = new Object();
	 
	if (Browser.Engine.trident) {
		obj.focus();
		var range = document.selection.createRange();
		var clone = range.duplicate();
		
		clone.moveToElementText(obj);
		clone.setEndPoint( 'EndToEnd', range );
		
		pos.start = clone.text.length - range.text.length;
		pos.end = clone.text.length - range.text.length + range.text.length;
	}
	
	else if(window.getSelection()) {
		pos.start = obj.selectionStart;
		pos.end = obj.selectionEnd;
	}
	 
	return pos;
}

function surroundHTML(before, after, target)
{
	
	var pos = getAreaRange(target);
	if(pos.start == pos.end){
		target.focus();
		return false;
	}else{
		var val = target.value;
		var range = val.slice(pos.start, pos.end);
		var beforeNode = val.slice(0, pos.start);
		var afterNode = val.slice(pos.end);
		var insertNode;
		
		if (range || pos.start != pos.end) {
			insertNode = before + range + after;
			target.value = beforeNode + insertNode + afterNode;
		}
		 
		else if (pos.start == pos.end) {
			insertNode = before + after;
			target.value = beforeNode + insertNode + afterNode;
		}
	}
}